
#include "type.h"
#include "const.h"
#include "protect.h"
#include "proto.h"
#include "string.h"
#include "proc.h"
#include "global.h"

PUBLIC void clock_handler(int req) {
    ticks++;
    p_proc_ready -> ticks--;

    if(k_reenter != 0) // 重入
        return;

    if(p_proc_ready -> ticks > 0) // 当前进程 ticks != 0 就不切换到其它进程
        return;

    schedule();
}

PUBLIC void milli_delay(int milli_sec) {
    int t = get_ticks();
    while(((get_ticks() - t) * 1000 / HZ) < milli_sec);
}

PUBLIC void init_clock() {
    // 初始化 8253 PIT
    out_byte(TIMER_MODE, RATE_GENERATOR);
    out_byte(TIMER0, (u8) (TIMER_FREQ/HZ));
    out_byte(TIMER0, (u8) ((TIMER_FREQ/HZ) >> 8));

    put_irq_handler(CLOCK_IRQ, clock_handler); // 设定时钟中断处理程序
    enable_irq(CLOCK_IRQ);                      // 让 8259A 可以接收时钟中断
}

